package com.mxt.moviedemo.controller;

import com.mxt.moviedemo.entity.Ticket;
import com.mxt.moviedemo.entity.User;
import com.mxt.moviedemo.service.TicketService;
import com.mxt.moviedemo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private TicketService ticketService;

    @RequestMapping("login")
    public Map<String, Object> login(@RequestParam("loginType") String loginType,
                                     @RequestParam("identifier") String identifier,
                                     @RequestParam("password") String password) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = null;
            if ("phone".equals(loginType)) {
                user = userService.loginForPhone(identifier, password);
            } else if ("email".equals(loginType)) {
                user = userService.loginForEmail(identifier, password);
            }

            if (user != null) {
                // 登录成功，返回包含用户名和跳转信息的数据
                result.put("success", true);
                result.put("username", user.getUname());
                result.put("redirectUrl", "/successPage");
            } else {
                result.put("success", false);
                result.put("error", "手机号/邮箱或密码错误");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "登录失败：" + e.getMessage());
        }
        return result;
    }

    @PostMapping("register")
    public Map<String, Object> register(@RequestBody User user) {
        logger.info("Received user for registration: {}", user);
        Map<String, Object> result = new HashMap<>();
        try {
            // 简单的表单验证
            if (user.getUname() == null || user.getPassword() == null) {
                result.put("success", false);
                result.put("message", "用户名和密码不能为空");
                return result;
            }
            user.setRole("用户");
            user.setBalance("0");
            int rows = userService.registerUser(user);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "注册成功");
            } else {
                result.put("success", false);
                result.put("message", "注册失败");
            }
        } catch (Exception e) {
            logger.error("Registration error: ", e);
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
        }
        return result;
    }
    @GetMapping("info")
    public Map<String, Object> getUserInfo(@RequestParam("username") String uname) {
        logger.info("获取用户信息，用户名：{}", uname);
        Map<String, Object> result = new HashMap<>();

        try {
            User user = userService.getUserByUsername(uname);
            logger.info("获取到的用户信息：{}", user);
            if (user != null) {
                result.put("success", true);
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("error", "未找到该用户");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "查询用户信息失败：" + e.getMessage());
        }
        return result;
    }
    @GetMapping("searchUname")
    public Map<String, Object> searchUname(@RequestParam("username") String uname) {
        logger.info("获取用户信息，用户名：{}", uname);
        Map<String, Object> result = new HashMap<>();

        try {
            List<User> user = userService.searchUsersByName(uname);
            if (user != null) {
                result.put("success", true);
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("error", "未找到该用户");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "查询用户信息失败：" + e.getMessage());
        }
        return result;
    }

    @GetMapping("orders")
    public Map<String, Object> getUserOrders(@RequestParam("username") String uname) {
        logger.info("获取用户信息，用户名：{}", uname);

        Map<String, Object> result = new HashMap<>();
        try {
            List<Ticket> tickets = ticketService.getTicketsByUsername(uname);
            if (tickets != null) {
                result.put("success", true);
                result.put("tickets", tickets);
            } else {
                result.put("success", false);
                result.put("error", "未找到该用户的订单信息");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "查询订单信息失败：" + e.getMessage());
        }
        return result;
    }
    @PostMapping("updateUsername")
    public Map<String, Object> updateUsername(@RequestBody Map<String, String> request) {
        logger.info("Received request to update username: {}", request);
        Map<String, Object> result = new HashMap<>();
        try {
            String username = request.get("username");
            String newUsername = request.get("newUsername");
            logger.info("旧用户名: {}, 新用户名: {}", username, newUsername);

            User user = userService.getUserByUsername(username);
            if (user == null) {
                result.put("success", false);
                result.put("message", "未找到该用户");
                return result;
            }

            user.setUname(newUsername);
            int rows = userService.updateUser(user);
            if (rows > 0) {
                // 调用更新订单表用户名的方法
                userService.updateTicketUsername(username,newUsername,user);
                result.put("success", true);
                result.put("message", "用户名修改成功");
                // 刷新用户信息
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("message", "用户名修改失败");
            }
        } catch (Exception e) {
            logger.error("Update username error: ", e);
            result.put("success", false);
            result.put("message", "用户名修改失败：" + e.getMessage());
        }
        return result;
    }
    @PostMapping("updatePassword")
    public Map<String, Object> updatePassword(@RequestBody Map<String, String> request) {
        logger.info("Received request to update address: {}", request);
        Map<String, Object> result = new HashMap<>();
        try {
            String username = request.get("username");
            String newPassword = request.get("newPassword");

            User user = userService.getUserByUsername(username);
            if (user == null) {
                result.put("success", false);
                result.put("message", "未找到该用户");
                return result;
            }

            user.setPassword(newPassword);
            int rows = userService.updateUser(user);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "密码修改成功");
                // 刷新用户信息
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("message", "密码修改失败");
            }
        } catch (Exception e) {
            logger.error("Update address error: ", e);
            result.put("success", false);
            result.put("message", "密码修改失败：" + e.getMessage());
        }
        return result;
    }

    @PostMapping("updateAddress")
    public Map<String, Object> updateAddress(@RequestBody Map<String, String> request) {
        logger.info("Received request to update address: {}", request);
        Map<String, Object> result = new HashMap<>();
        try {
            String username = request.get("username");
            String newAddress = request.get("newAddress");

            User user = userService.getUserByUsername(username);
            if (user == null) {
                result.put("success", false);
                result.put("message", "未找到该用户");
                return result;
            }

            user.setAddress(newAddress);
            int rows = userService.updateUser(user);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "地址修改成功");
                // 刷新用户信息
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("message", "地址修改失败");
            }
        } catch (Exception e) {
            logger.error("Update address error: ", e);
            result.put("success", false);
            result.put("message", "地址修改失败：" + e.getMessage());
        }
        return result;
    }

    @PostMapping("updateEmail")
    public Map<String, Object> updateEmail(@RequestBody Map<String, String> request) {
        logger.info("Received request to update email: {}", request);
        Map<String, Object> result = new HashMap<>();
        try {
            String username = request.get("username");
            String newEmail = request.get("newEmail");

            User user = userService.getUserByUsername(username);
            if (user == null) {
                result.put("success", false);
                result.put("message", "未找到该用户");
                return result;
            }

            user.setEmail(newEmail);
            int rows = userService.updateUser(user);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "邮箱修改成功");
                // 刷新用户信息
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("message", "邮箱修改失败");
            }
        } catch (Exception e) {
            logger.error("Update email error: ", e);
            result.put("success", false);
            result.put("message", "邮箱修改失败：" + e.getMessage());
        }
        return result;
    }
    @PostMapping("/recharge")
    public Map<String, Object> recharge(@RequestBody Map<String, Object> request) {
        String username = (String) request.get("username");
        double amount = Double.parseDouble(request.get("amount").toString());
        logger.info("接收到的充值参数 - 用户名: {}, 金额: {}", username, amount);
        Map<String, Object> response = new HashMap<>();
        if (userService.recharge(username, amount)) {
            response.put("success", true);
            response.put("message", "充值成功");
        } else {
            response.put("success", false);
            response.put("message", "充值失败");
        }
        return response;
    }

    @PostMapping("updateUserInfo")
    public Map<String, Object> updateUserInfo(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        System.out.println(user.getUname());
        System.out.println(user.getAddress());
        System.out.println(user.getBalance());
        System.out.println(user.getPhone());
        System.out.println(user.getPassword());
        try {
            // 调用服务层方法更新用户信息
            int rows = userService.updateUser(user);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "用户信息更新成功");
            } else {
                result.put("success", false);
                result.put("message", "用户信息更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户信息失败: ", e);
            result.put("success", false);
            result.put("message", "用户信息更新失败：" + e.getMessage());
        }
        return result;
    }
    @PostMapping("deleteUser")
    public Map<String, Object> deleteUser(@RequestBody Map<String, Integer> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer uuid = request.get("uuid");
            if (userService.deleteUserByUuid(uuid)) {
                result.put("success", true);
                result.put("message", "用户信息删除成功");
            } else {
                result.put("success", false);
                result.put("message", "用户信息删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除用户信息失败：" + e.getMessage());
        }
        return result;
    }

    @GetMapping("/getUserId")
    public Map<String, Object> getUserId(@RequestParam("uname") String uname) {
        Map<String, Object> result = new HashMap<>();
        try {
            int uuid = userService.getUserIdByUsername(uname);
            if (uuid > 0) {
                result.put("success", true);
                result.put("uuid", uuid);
            } else {
                result.put("success", false);
                result.put("message", "未找到该用户");
            }
        } catch (Exception e) {
            logger.error("获取用户 ID 错误: ", e);
            result.put("success", false);
            result.put("message", "获取用户 ID 失败：" + e.getMessage());
        }
        return result;
    }

}